package com.example.mybatis.configuration;

import com.example.mybatis.interceptors.WebCorsInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebCorsConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(WebCorsConfiguration.class);
    private String origin = "http://localhost:3000";
    @Bean
    public WebMvcConfigurer webMvcConfigure(){
        return new WebMvcConfigurer(){
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                logger.info("配置跨域信息");
                //添加映射路径
                registry.addMapping("/springboot/**")
                        .allowedOrigins(origin)    //放行哪些原始域
                        .allowCredentials(true)    //是否发送Cookie信息
                        .maxAge(3600)
                        .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")  //放行哪些请求方式
                        .allowedHeaders("Content-Disposition","Authorization")     //放行哪些请求头
                        .exposedHeaders("Content-Disposition");  //暴露哪些非默认的头部信息

            }

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                logger.info("添加拦截器");
                HandlerInterceptor interceptor = new WebCorsInterceptor();
                registry.addInterceptor(interceptor);
            }

        };
    }
}
